package com.example.emqx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.emqx.entity.EmqAcl;
import com.example.emqx.pojo.AclRequest;
import com.example.emqx.service.EmqAclService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * File: AuthController.java
 * Author: liufudong@szyh-smart.com
 * Date: 2024/8/29
 * Description: AuthController class.
 * 文档在https://docs.emqx.com/zh/emqx/latest/access-control/authn/http.html
 * <p>
 * 要订阅才会触发该事件
 */
@RestController
@RequestMapping("/mqtt")
@Slf4j
public class AclController {
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private EmqAclService emqAclService;

    @PostConstruct
    public void init() {
    }

    /**
     * 成功响应状态码
     * <p>
     * shell
     * 200 or 204
     * 如果请求失败或返回其他状态码，授权检查器将被忽略。
     * <p>
     * 成功响应 body (JSON):
     * <p>
     * Name	类型	是否必须	描述
     * result	Enum	是	`allow
     * json
     * {
     * "result": "deny"
     * }
     *
     * @param aclRequest
     * @return
     */
    @PostMapping(path = "/acl")
    public ResponseEntity<Map<String, Object>> acl(
            @RequestBody AclRequest aclRequest
    ) {
        String result = "allow";
        try {
            log.info("acl map:{}", objectMapper.writeValueAsString(aclRequest));
            LambdaQueryWrapper<EmqAcl> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(EmqAcl::getUsername, aclRequest.getUsername());
            EmqAcl emqAcl = emqAclService.getOne(lambdaQueryWrapper);
            log.info("acl emqAcl:{}", objectMapper.writeValueAsString(emqAcl));
            if (emqAcl != null) {
                result = "allow";
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        Map<String, Object> response = new HashMap<>();
        response.put("result", result);
        return ResponseEntity.ok(response);
    }

}
